package com.inche.camerademo;

import static android.graphics.ImageFormat.JPEG;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.*;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.inche.camerademo.Util.CameraPreviewAdjuster;
import com.inche.camerademo.Util.size.surfaceSize;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;

public class Demo3Activity extends AppCompatActivity implements View.OnClickListener {


    public static final String TAG = "Camera2Demo";
    public static final int RC_CAMERA = 101;

    private TextureView mTextureView;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private surfaceSize mSurfaceSize;          // 保存计算出的最佳预览尺寸
    private CameraManager cameraManager;
    private CameraDevice mCameraDevice;
    private CameraDevice.StateCallback mCameraCallback;
    private CameraCaptureSession mCameraCaptureSession;  // session通道对象
    private ImageReader mImageReader;
    private CameraPreviewAdjuster cameraPreviewAdjuster;
    private  CameraCharacteristics characteristics;
    /* ================== 生命周期 ================== */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo3);
        mTextureView = findViewById(R.id.sjm);
        findViewById(R.id.btnOpen).setOnClickListener(this);
        findViewById(R.id.btnClose).setOnClickListener(this);
        findViewById(R.id.btnCapture).setOnClickListener(this);
        cameraPreviewAdjuster = new CameraPreviewAdjuster();
        startBackGround();
        initTextureListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        closeCamera();
        // 这里可以关闭相机释放资源
    }

    /* ================== TextureView 监听 ================== */
    private void initTextureListener() {
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                try {
                    openCamera();
                } catch (CameraAccessException e) {
                    throw new RuntimeException(e);
                }
                mSurfaceSize =  cameraPreviewAdjuster.getSurfaceSize(characteristics,width,height);
                if (mSurfaceSize != null) {
                    Log.d(TAG, "最佳预览尺寸：" + mSurfaceSize.getWidth() + "x" + mSurfaceSize.getHeight());
                    // 核心用法：给 SurfaceTexture 设置缓冲区大小
                    surface.setDefaultBufferSize(mSurfaceSize.getWidth(), mSurfaceSize.getHeight());
                }else {
                    //  fallback：用默认尺寸
                    mSurfaceSize = new surfaceSize(width, height);
                    surface.setDefaultBufferSize(width, height);
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
                // ===新增=== 旋转/分屏后重新适配
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) { return false; }
            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {}
        });
    }

    /* ================== 打开相机 ================== */
    public void openCamera() throws CameraAccessException {
        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String cameraId = cameraManager.getCameraIdList()[0];
        initCameraCallback();
        characteristics = cameraManager.getCameraCharacteristics(cameraId);
        if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, RC_CAMERA);
            return;
        }
        cameraManager.openCamera(cameraId, mCameraCallback, mHandler);
    }

    /* ================== 后台线程 ================== */
    public void startBackGround() {
        mHandlerThread = new HandlerThread("cameraBackground");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
    }

    /* ================== 相机状态回调 ================== */
    private void initCameraCallback() {
        mCameraCallback = new CameraDevice.StateCallback() {
            @Override
            public void onOpened(@NonNull CameraDevice cameraDevice) {
                mCameraDevice = cameraDevice;
                startPreview();        // 创建会话
            }
            @Override public void onDisconnected(@NonNull CameraDevice camera) {}
            @Override public void onError(@NonNull CameraDevice camera, int error) {}
        };
    }

    /* ================== 开始预览（原逻辑未动） ================== */
    private void startPreview() {
        try {
            Surface surface = new Surface(mTextureView.getSurfaceTexture());
            OutputConfiguration outConfig = new OutputConfiguration(surface);
            List<OutputConfiguration> outputs = Arrays.asList(outConfig);
            Executor executor = r -> mHandler.post(r);
            CameraCaptureSession.StateCallback sessionCallback = new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    try {
                        mCameraCaptureSession = session;
//                        这里去告诉底层 这次请求是干嘛的 CameraDevice.TEMPLATE_PREVIEW 这个配置是和系统底层约定好的参数
                        CaptureRequest.Builder builder =
                                mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
//                        下发surface 让底层返回的数据绑定到这个surface中
                        builder.addTarget(surface);
//                        不断的请求数据
                        session.setRepeatingRequest(builder.build(), null, mHandler);
                    } catch (CameraAccessException e) { throw new RuntimeException(e); }
                }
                @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) {}
            };
//           把输出 Surface、回调线程、状态监听打包成配置
            SessionConfiguration mSessionConfiguration = new SessionConfiguration(SessionConfiguration.SESSION_REGULAR, outputs, executor, sessionCallback);
//          通知 CameraService 按配置建立会话（仅配置流，还未开始出图）
            mCameraDevice.createCaptureSession(mSessionConfiguration);
        } catch (CameraAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btnOpen){
            try {
                openCamera();
            } catch (CameraAccessException e) {
                throw new RuntimeException(e);
            }
        }else if(v.getId() == R.id.btnClose){
            closeCamera();
        }else if(v.getId() == R.id.btn_capture){
            takePicture();
        }
    }

    public void takePicture(){
//    啦啦啦提交一下
//        水个提交
    }

    public void closeCamera(){
        if (mCameraCaptureSession != null){
            mCameraCaptureSession.close();
            mCameraCaptureSession = null;
        }
        if (mCameraDevice !=null){
            mCameraDevice.close();
            mCameraDevice = null;
        }
    }


}